//
//  NSDate+Extension.m
//  KuBer
//
//  Created by 吴双 on 15/12/4.
//  Copyright © 2015年 huaxu. All rights reserved.
//

#import "NSDate+Extension.h"
#import "NSDateFormatter+Category.h"

#define DATE_COMPONENTS (NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekOfYear |  NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal)
#define CURRENT_CALENDAR [NSCalendar currentCalendar]
#define MULocalizedString(key, comment) NSLocalizedStringFromTable(key, @"DateDescription", comment)

@implementation NSDate (Extension)

/*距离当前的时间间隔描述*/
- (NSString *)timeIntervalDescription
{
	NSTimeInterval timeInterval = -[self timeIntervalSinceNow];
	if (timeInterval < 60) {
		return MULocalizedString(@"NSDateCategory.text1", @"");
	} else if (timeInterval < D_HOUR) {
		return [NSString stringWithFormat:MULocalizedString(@"NSDateCategory.text2", @""), timeInterval / 60];
	} else if (timeInterval < D_DAY) {
		return [NSString stringWithFormat:MULocalizedString(@"NSDateCategory.text3", @""), timeInterval / 3600];
	} else if (timeInterval < D_MONTH) {//30天内
		return [NSString stringWithFormat:MULocalizedString(@"NSDateCategory.text4", @""), timeInterval / 86400];
	} else if (timeInterval < D_YEAR) {//30天至1年内
		NSDateFormatter *dateFormatter = [NSDateFormatter dateFormatterWithFormat:MULocalizedString(@"NSDateCategory.text5", @"")];
		return [dateFormatter stringFromDate:self];
	} else {
		return [NSString stringWithFormat:MULocalizedString(@"NSDateCategory.text6", @""), timeInterval / 31536000];
	}
}

/*精确到分钟的日期描述*/
- (NSString *)minuteDescription
{
	NSDateFormatter *dateFormatter = [NSDateFormatter dateFormatterWithFormat:@"yyyy-MM-dd"];
	
	NSString *theDay = [dateFormatter stringFromDate:self];//日期的年月日
	NSString *currentDay = [dateFormatter stringFromDate:[NSDate date]];//当前年月日
	if ([theDay isEqualToString:currentDay]) {//当天
		[dateFormatter setDateFormat:@"ah:mm"];
		return [dateFormatter stringFromDate:self];
	} else if ([[dateFormatter dateFromString:currentDay] timeIntervalSinceDate:[dateFormatter dateFromString:theDay]] == 86400) {//昨天
		[dateFormatter setDateFormat:@"ah:mm"];
		return [NSString stringWithFormat:MULocalizedString(@"NSDateCategory.text7", @""), [dateFormatter stringFromDate:self]];
	} else if ([[dateFormatter dateFromString:currentDay] timeIntervalSinceDate:[dateFormatter dateFromString:theDay]] < 86400 * 7) {//间隔一周内
		[dateFormatter setDateFormat:@"EEEE ah:mm"];
		return [dateFormatter stringFromDate:self];
	} else {//以前
		[dateFormatter setDateFormat:@"yyyy-MM-dd ah:mm"];
		return [dateFormatter stringFromDate:self];
	}
}

/*标准时间日期描述*/
-(NSString *)formattedTime{
	NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
	[formatter setDateFormat:@"YYYY-MM-dd"];
	NSString * dateNow = [formatter stringFromDate:[NSDate date]];
	NSDateComponents *components = [[NSDateComponents alloc] init];
	[components setDay:[[dateNow substringWithRange:NSMakeRange(8,2)] intValue]];
	[components setMonth:[[dateNow substringWithRange:NSMakeRange(5,2)] intValue]];
	[components setYear:[[dateNow substringWithRange:NSMakeRange(0,4)] intValue]];
	NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
	NSDate *date = [gregorian dateFromComponents:components]; //今天 0点时间
 
	NSInteger hour = [self hoursAfterDate:date];
	NSDateFormatter *dateFormatter = nil;
	NSString *ret = @"";
	
	//hasAMPM==TURE为12小时制，否则为24小时制
	NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
	NSRange containsA = [formatStringForHours rangeOfString:@"a"];
//	BOOL hasAMPM = containsA.location != NSNotFound;
	
//	if (!hasAMPM) { //24小时制
//		if (hour <= 24 && hour >= 0) {
//			dateFormatter = [NSDateFormatter dateFormatterWithFormat:@"HH:mm"];
//		}else if (hour < 0 && hour >= -24) {
//			dateFormatter = [NSDateFormatter dateFormatterWithFormat:MULocalizedString(@"NSDateCategory.text8", @"")];
//		}else {
//			dateFormatter = [NSDateFormatter dateFormatterWithFormat:@"yyyy-MM-dd HH:mm"];
//		}
//	}else {
//		if (hour >= 0 && hour <= 6) {
//			dateFormatter = [NSDateFormatter dateFormatterWithFormat:MULocalizedString(@"NSDateCategory.text9", @"")];
//		}else if (hour > 6 && hour <=11 ) {
//			dateFormatter = [NSDateFormatter dateFormatterWithFormat:MULocalizedString(@"NSDateCategory.text10", @"")];
//		}else if (hour > 11 && hour <= 17) {
//			dateFormatter = [NSDateFormatter dateFormatterWithFormat:MULocalizedString(@"NSDateCategory.text11", @"")];
//		}else if (hour > 17 && hour <= 24) {
//			dateFormatter = [NSDateFormatter dateFormatterWithFormat:MULocalizedString(@"NSDateCategory.text12", @"")];
//		}else if (hour < 0 && hour >= -24){
//			dateFormatter = [NSDateFormatter dateFormatterWithFormat:MULocalizedString(@"NSDateCategory.text13", @"")];
//		}else  {
//			dateFormatter = [NSDateFormatter dateFormatterWithFormat:@"yyyy-MM-dd HH:mm"];
//        }
//        dateFormatter = [NSDateFormatter dateFormatterWithFormat:@"yyyy-MM-dd"];
//	}
    dateFormatter = [NSDateFormatter dateFormatterWithFormat:@"yyyy-MM-dd"];
    
	ret = [dateFormatter stringFromDate:self];
	return ret;
}

/*格式化日期描述*/
- (NSString *)formattedDateDescription
{
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	
	[dateFormatter setDateFormat:@"yyyy-MM-dd"];
	NSString *theDay = [dateFormatter stringFromDate:self];//日期的年月日
	NSString *currentDay = [dateFormatter stringFromDate:[NSDate date]];//当前年月日
	
	NSInteger timeInterval = -[self timeIntervalSinceNow];
	if (timeInterval < 60) {
		return MULocalizedString(@"NSDateCategory.text1", @"");
	} else if (timeInterval < 3600) {//1小时内
		return [NSString stringWithFormat:MULocalizedString(@"NSDateCategory.text2", @""), timeInterval / 60];
	} else if (timeInterval < 21600) {//6小时内
		return [NSString stringWithFormat:MULocalizedString(@"NSDateCategory.text3", @""), timeInterval / 3600];
	} else if ([theDay isEqualToString:currentDay]) {//当天
		[dateFormatter setDateFormat:@"HH:mm"];
		return [NSString stringWithFormat:MULocalizedString(@"NSDateCategory.text14", @""), [dateFormatter stringFromDate:self]];
	} else if ([[dateFormatter dateFromString:currentDay] timeIntervalSinceDate:[dateFormatter dateFromString:theDay]] == 86400) {//昨天
		[dateFormatter setDateFormat:@"HH:mm"];
		return [NSString stringWithFormat:MULocalizedString(@"NSDateCategory.text7", @""), [dateFormatter stringFromDate:self]];
	} else {//以前
		[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
		return [dateFormatter stringFromDate:self];
	}
}
+(NSString *)secondTranfer:(float)second string:(NSString*)str
{
    str =str?str:@"";
    
    if(second < 60) {
        return [NSString stringWithFormat:@"%@%.2f秒",str,second];
    } else if(second >= 60 && second < 60 * 60) {//分钟
        int mm = second/60;
        int ss = (int)second%60;
        if (ss==0) {
            return [NSString stringWithFormat:@"%@%d分钟",str,mm];
        }
        return [NSString stringWithFormat:@"%@%d分钟%d秒",str,mm,ss];
        
    } else if(second >= 60 * 60 ) {//小时&& second < 24 * 60 * 60
        int hh = second/(60 * 60);
        int mm = second - hh*3600;
        
        if (mm >= 60 && mm < 60 * 60) {
            int m = mm/60;
            int ss = mm%60;
            if (ss==0) {
                return [NSString stringWithFormat:@"%d小时%d分钟",hh,m];
            }
            return [NSString stringWithFormat:@"%d小时%d分钟%d秒",hh,m,ss];
        }else
        {
            if (mm==0) {
                return [NSString stringWithFormat:@"%d小时",hh];
            }
            return [NSString stringWithFormat:@"%d小时%d秒",hh,mm];
            
        }
        
    }
    
    return [NSString stringWithFormat:@"%.2f秒",second];
}
+(NSString *)secondIntosHours:(float)second
{
    return  [self secondTranfer:second string:@""];
}

/**
 * 判断当前时间是否处于某个时间段内
 *
 * @param startTime 开始时间
 * @param expireTime 结束时间
 */
+ (BOOL)validateWithStartTime:(NSString *)startTime withExpireTime:(NSString *)expireTime{
    
    if (startTime == nil || expireTime == nil ) {
        return NO;
    }
    NSDate *today = [NSDate date];
    NSDate *start =  [NSDate dateWithTimeIntervalSince1970:[startTime doubleValue]/1000];
    NSDate *expire = [NSDate dateWithTimeIntervalSince1970:[expireTime doubleValue]/1000];
    NSLog(@"statr = %@ , %@",start,expire);
    if ([today compare:start] == NSOrderedDescending && [today compare:expire] == NSOrderedAscending) {
        return YES;
    }
    return NO;
}

+ (BOOL)validateWithStartTime:(NSString *)startTime endTime:(NSString *)expireTime  form:(NSString *)form {
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    dateFormatter.dateFormat = form;
    
    NSDate *s =   [dateFormatter dateFromString:startTime];
    NSDate *e =   [dateFormatter dateFromString:expireTime];
    
    NSComparisonResult result = [s compare:e];
    if (result == NSOrderedAscending || result ==NSOrderedSame) {
        return YES;
    }
    return NO;
}
+ (BOOL)validateWithStartTime:(NSString *)startTime endTime:(NSString *)expireTime {

    return [self validateWithStartTime:startTime endTime:expireTime form:@"yyyy-MM-dd"];
}

/**
 * 判断当前时间是否处于某个时间段内
 *
 * @param startDate 开始时间
 * @param expireDate 结束时间
 */
+ (BOOL)validateWithStartDate:(NSDate *)startDate withExpireDate:(NSDate *)expireDate {
    
    if (startDate == nil || expireDate == nil ) {
        return NO;
    }
    NSDate *today = [NSDate date];
    if ([today compare:startDate] == NSOrderedDescending && [today compare:expireDate] == NSOrderedAscending) {
        return YES;
    }
    return NO;
}

- (double)timeIntervalSince1970InMilliSecond {
	double ret;
	ret = [self timeIntervalSince1970] * 1000;
	
	return ret;
}

+ (NSDate *)dateWithTimeIntervalInMilliSecondSince1970:(double)timeIntervalInMilliSecond {
	NSDate *ret = nil;
	double timeInterval = timeIntervalInMilliSecond;
	// judge if the argument is in secconds(for former data structure).
	if(timeIntervalInMilliSecond > 140000000000) {
		timeInterval = timeIntervalInMilliSecond / 1000;
	}
	ret = [NSDate dateWithTimeIntervalSince1970:timeInterval];
	
	return ret;
}

+ (NSString *)formattedTimeFromTimeInterval:(long long)time{
	return [[NSDate dateWithTimeIntervalInMilliSecondSince1970:time] formattedTime];
}

#pragma mark Relative Dates

+ (NSDate *) dateWithDaysFromNow: (NSInteger) days
{
	// Thanks, Jim Morrison
	return [[NSDate date] dateByAddingDays:days];
}

+ (NSDate *) dateWithDaysBeforeNow: (NSInteger) days
{
	// Thanks, Jim Morrison
	return [[NSDate date] dateBySubtractingDays:days];
}
+ (NSString *)getDateComponentsYMDHMS:(NSDateComponents *)com{
    NSDateComponents *components =com;
    return [NSString stringWithFormat:@"%d-%.2d-%.2d %.2d:%.2d:%.2d",(int)components.year,(int)components.month,(int)components.day,(int)components.hour,(int)components.minute,(int)components.second];
    
}
- (NSString *)getDateStringYMDHMS{
    
        NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:self];
    return [NSString stringWithFormat:@"%d-%.2d-%.2d %.2d:%.2d:%.2d",(int)components.year,(int)components.month,(int)components.day,(int)components.hour,(int)components.minute,(int)components.second];
}
- (NSString *)getDateStringYMD {
        NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
        NSDateComponents *components = [calendar components:NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:self];
    return [NSString stringWithFormat:@"%d-%.2d-%.2d",(int)components.year,(int)components.month,(int)components.day];
}
+ (NSString *)getDateStringYM {
    NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:self];
    return [NSString stringWithFormat:@"%d-%.2d",(int)components.year,(int)components.month];
}

+ (NSDate *) dateTomorrow
{
	return [NSDate dateWithDaysFromNow:1];
}

+ (NSDate *) dateYesterday
{
	return [NSDate dateWithDaysBeforeNow:1];
}

+ (NSDate *) dateWithHoursFromNow: (NSInteger) dHours
{
	NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] + D_HOUR * dHours;
	NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	return newDate;
}

+ (NSDate *) dateWithHoursBeforeNow: (NSInteger) dHours
{
	NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] - D_HOUR * dHours;
	NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	return newDate;
}

+ (NSDate *) dateWithMinutesFromNow: (NSInteger) dMinutes
{
	NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] + D_MINUTE * dMinutes;
	NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	return newDate;
}

+ (NSDate *) dateWithMinutesBeforeNow: (NSInteger) dMinutes
{
	NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] - D_MINUTE * dMinutes;
	NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	return newDate;
}

#pragma mark Comparing Dates

- (BOOL) isEqualToDateIgnoringTime: (NSDate *) aDate
{
	NSDateComponents *components1 = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self];
	NSDateComponents *components2 = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:aDate];
	return ((components1.year == components2.year) &&
			(components1.month == components2.month) &&
			(components1.day == components2.day));
}

- (BOOL) isToday
{
	return [self isEqualToDateIgnoringTime:[NSDate date]];
}

- (BOOL) isTomorrow
{
	return [self isEqualToDateIgnoringTime:[NSDate dateTomorrow]];
}

- (BOOL) isYesterday
{
	return [self isEqualToDateIgnoringTime:[NSDate dateYesterday]];
}

// This hard codes the assumption that a week is 7 days
- (BOOL) isSameWeekAsDate: (NSDate *) aDate
{
	NSDateComponents *components1 = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self];
	NSDateComponents *components2 = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:aDate];
	
	// Must be same week. 12/31 and 1/1 will both be week "1" if they are in the same week
	if (components1.weekOfYear != components2.weekOfYear) return NO;
	
	// Must have a time interval under 1 week. Thanks @aclark
	return (fabs([self timeIntervalSinceDate:aDate]) < D_WEEK);
}

- (BOOL) isThisWeek
{
	return [self isSameWeekAsDate:[NSDate date]];
}

- (BOOL) isNextWeek
{
	NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] + D_WEEK;
	NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	return [self isSameWeekAsDate:newDate];
}

- (BOOL) isLastWeek
{
	NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] - D_WEEK;
	NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	return [self isSameWeekAsDate:newDate];
}

// Thanks, mspasov
- (BOOL) isSameMonthAsDate: (NSDate *) aDate
{
	NSDateComponents *components1 = [CURRENT_CALENDAR components:NSCalendarUnitYear | NSCalendarUnitMonth fromDate:self];
	NSDateComponents *components2 = [CURRENT_CALENDAR components:NSCalendarUnitYear | NSCalendarUnitMonth fromDate:aDate];
	return ((components1.month == components2.month) &&
			(components1.year == components2.year));
}

- (BOOL) isThisMonth
{
	return [self isSameMonthAsDate:[NSDate date]];
}

- (BOOL) isSameYearAsDate: (NSDate *) aDate
{
	NSDateComponents *components1 = [CURRENT_CALENDAR components:NSCalendarUnitYear fromDate:self];
	NSDateComponents *components2 = [CURRENT_CALENDAR components:NSCalendarUnitYear fromDate:aDate];
	return (components1.year == components2.year);
}

- (BOOL) isThisYear
{
	// Thanks, baspellis
	return [self isSameYearAsDate:[NSDate date]];
}

- (BOOL) isNextYear
{
	NSDateComponents *components1 = [CURRENT_CALENDAR components:NSCalendarUnitYear fromDate:self];
	NSDateComponents *components2 = [CURRENT_CALENDAR components:NSCalendarUnitYear fromDate:[NSDate date]];
	
	return (components1.year == (components2.year + 1));
}

- (BOOL) isLastYear
{
	NSDateComponents *components1 = [CURRENT_CALENDAR components:NSCalendarUnitYear fromDate:self];
	NSDateComponents *components2 = [CURRENT_CALENDAR components:NSCalendarUnitYear fromDate:[NSDate date]];
	
	return (components1.year == (components2.year - 1));
}

- (BOOL) isEarlierThanDate: (NSDate *) aDate
{
	return ([self compare:aDate] == NSOrderedAscending);
}

- (BOOL) isLaterThanDate: (NSDate *) aDate
{
	return ([self compare:aDate] == NSOrderedDescending);
}

// Thanks, markrickert
- (BOOL) isInFuture
{
	return ([self isLaterThanDate:[NSDate date]]);
}

// Thanks, markrickert
- (BOOL) isInPast
{
	return ([self isEarlierThanDate:[NSDate date]]);
}


#pragma mark Roles
- (BOOL) isTypicallyWeekend
{
	NSDateComponents *components = [CURRENT_CALENDAR components:NSCalendarUnitWeekday fromDate:self];
	if ((components.weekday == 1) ||
		(components.weekday == 7))
		return YES;
	return NO;
}

- (BOOL) isTypicallyWorkday
{
	return ![self isTypicallyWeekend];
}

#pragma mark Adjusting Dates

- (NSDate *) dateByAddingDays: (NSInteger) dDays
{
	NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + D_DAY * dDays;
	NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	return newDate;
}

- (NSDate *)df_dateByAddingDays:(NSInteger)dDays
{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setDay:dDays];
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:self options:0];
    return newDate;
}


- (NSDate *) dateBySubtractingDays: (NSInteger) dDays
{
	return [self dateByAddingDays: (dDays * -1)];
}

- (NSDate *) dateByAddingHours: (NSInteger) dHours
{
	NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + D_HOUR * dHours;
	NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	return newDate;
}

- (NSDate *) dateBySubtractingHours: (NSInteger) dHours
{
	return [self dateByAddingHours: (dHours * -1)];
}

- (NSDate *) dateByAddingMinutes: (NSInteger) dMinutes
{
	NSTimeInterval aTimeInterval = [self timeIntervalSinceReferenceDate] + D_MINUTE * dMinutes;
	NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	return newDate;
}

- (NSDate *) dateBySubtractingMinutes: (NSInteger) dMinutes
{
	return [self dateByAddingMinutes: (dMinutes * -1)];
}

- (NSDate *) dateAtStartOfNextHour
{
    NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self];
        components.minute = 0;
        components.second = 0;
        return [[CURRENT_CALENDAR dateFromComponents:components] dateByAddingHours:1];
}

- (NSDate *) dateAtStartOfDay
{
	NSDateComponents *components = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self];
	components.hour = 0;
	components.minute = 0;
	components.second = 0;
	return [CURRENT_CALENDAR dateFromComponents:components];
}

- (NSDateComponents *) componentsWithOffsetFromDate: (NSDate *) aDate
{
	NSDateComponents *dTime = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:aDate toDate:self options:0];
	return dTime;
}

#pragma mark Retrieving Intervals

- (NSInteger) minutesAfterDate: (NSDate *) aDate
{
	NSTimeInterval ti = [self timeIntervalSinceDate:aDate];
	return (NSInteger) (ti / D_MINUTE);
}

- (NSInteger) minutesBeforeDate: (NSDate *) aDate
{
	NSTimeInterval ti = [aDate timeIntervalSinceDate:self];
	return (NSInteger) (ti / D_MINUTE);
}

- (NSInteger) hoursAfterDate: (NSDate *) aDate
{
	NSTimeInterval ti = [self timeIntervalSinceDate:aDate];
	return (NSInteger) (ti / D_HOUR);
}

- (NSInteger) hoursBeforeDate: (NSDate *) aDate
{
	NSTimeInterval ti = [aDate timeIntervalSinceDate:self];
	return (NSInteger) (ti / D_HOUR);
}

- (NSInteger) daysAfterDate: (NSDate *) aDate
{
	NSTimeInterval ti = [self timeIntervalSinceDate:aDate];
	return (NSInteger) (ti / D_DAY);
}

- (NSInteger) daysBeforeDate: (NSDate *) aDate
{
	NSTimeInterval ti = [aDate timeIntervalSinceDate:self];
	return (NSInteger) (ti / D_DAY);
}

// Thanks, dmitrydims
// I have not yet thoroughly tested this
- (NSInteger)distanceInDaysToDate:(NSDate *)anotherDate
{
	NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
	NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay fromDate:self toDate:anotherDate options:0];
	return components.day;
}

#pragma mark Decomposing Dates

- (NSInteger)nearestHour {
	NSTimeInterval aTimeInterval = [[NSDate date] timeIntervalSinceReferenceDate] + D_MINUTE * 30;
	NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
	NSDateComponents *components = [CURRENT_CALENDAR components:NSCalendarUnitHour fromDate:newDate];
	return components.hour;
}

- (NSInteger)hour {
	return [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self].hour;
}

- (NSInteger)minute {
	return [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self].minute;
}

- (NSInteger)seconds {
	return [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self].second;
}

- (NSInteger)day {
	return [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self].day;
}

- (NSInteger)month {
	return [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self].month;
}

- (NSInteger)weekOfMonth {
	return [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self].weekOfMonth;
}

- (NSInteger)weekOfYear {
	return [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self].weekOfYear;
}

- (NSInteger)weekday {
	return [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self].weekday;
}

- (NSInteger)nthWeekday { // e.g. 2nd Tuesday of the month is 2
	return [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self].weekdayOrdinal;
}

- (NSInteger)year {
	return [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self].year;
}
+ (NSInteger)numberOfDayInMonthWithDateStr:(NSString *)dateStr {
    NSDate * date = [self dateWithdateSr:dateStr];
    
    NSCalendar * calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 通过该方法计算特定日期月份的天数
    NSRange monthRange =  [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    
    return monthRange.length;
}

/**
 根据给出的日期获得NSDate
 
 @param dateStr 日期
 @return 对应的NSDate
 */
+ (NSDate *)dateWithdateSr:(NSString *)dateStr {
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    // 此处根据需求改对应的日期格式
    [dateFormatter setDateFormat:@"yyyy-MM"];
    NSDate * date = [dateFormatter dateFromString:dateStr];
    
    return date;
}

/// 根据给出的日期获得NSDate
/// @param dateStr 日期
/// @param format 格式化格式
+ (NSDate *)dateWithdateSr:(NSString *)dateStr format:(NSString *)format {
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    // 此处根据需求改对应的日期格式
    [dateFormatter setDateFormat:format];
    NSDate * date = [dateFormatter dateFromString:dateStr];
    
    return date;
}
/// 根据格式化获取当前时间对应的字符串
/// @param format 格式化格式
- (NSString *)dateStrWithformat:(NSString *)format {
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
    // 此处根据需求改对应的日期格式
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:self];
}
+ (NSTimeInterval)getZeroWithTimeInterverl:(NSTimeInterval)timeInterval {
    NSDate *originalDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFomater = [[NSDateFormatter alloc]init];
    dateFomater.dateFormat = @"yyyy年MM月dd日";
    NSString *original = [dateFomater stringFromDate:originalDate];
    NSDate *ZeroDate = [dateFomater dateFromString:original];
    return [ZeroDate timeIntervalSince1970];
}


/**
 *  获得与当前时间的差距
 */
- (NSDateComponents *)deltaWithNow {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitDay| NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    return [calendar components:unit fromDate:self toDate:[NSDate date] options:0];
}

@end
